package webflux2.handler;

import org.springframework.beans.factory.annotation.Autowired;
import webflux2.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import webflux2.repository.UserRepository;
import webflux2.util.CheckUtil;

import static org.springframework.http.MediaType.*;
import static org.springframework.web.reactive.function.server.ServerResponse.notFound;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

@Component
public class UserHandler {

    @Autowired
    private final UserRepository userRepository;

    public UserHandler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

//    public UserHandler(UserRepository userRepository){
//        this.userRepository = userRepository;
//    }

    /**
     * 得到所有用户
     */
    public Mono<ServerResponse> getAllUsers(ServerRequest request){
        return ok().contentType(APPLICATION_JSON)
                .body(userRepository.findAll(), User.class);
    }

    /**
     * 创建用户
     */
    public Mono<ServerResponse> createUser(ServerRequest request){
        Mono<User> user = request.bodyToMono(User.class);
        return user.flatMap(u ->{
            CheckUtil.checkName(u.getName());
            return ok().contentType(APPLICATION_JSON)
                    .body(userRepository.save(u), User.class);
        });
    }

    /**
     * 根据id删除用户
     */
    public Mono<ServerResponse> deleteUserById(ServerRequest request){
        String id = request.pathVariable("id");
        return userRepository.findById(id)
                .flatMap(user -> userRepository.delete(user))
                .then(ok().build())
                .switchIfEmpty(notFound().build());
    }
}
